package cn.jjxx.modules.sbfb.controller;

import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.MapBeanUtil;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.annotations.TableName;

import org.framework.superutil.thirdparty.excel.ExcelDataFormatter;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import cn.jjxx.modules.common.bean.UploadExcel;
import cn.jjxx.modules.eas.entity.EasTOrgBaseunit;
import cn.jjxx.modules.eas.service.IEasTOrgBaseunitService;
import cn.jjxx.modules.sys.entity.Dict;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.service.IDictService;
import cn.jjxx.modules.sys.utils.UserUtils;
import cn.jjxx.modules.xmgl.entity.XmglJtProgress;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.modules.sbfb.entity.EqEquipDesc;
import cn.jjxx.modules.sbfb.entity.EqMixStation;
import cn.jjxx.modules.sbfb.service.IEqEquipDescService;
import cn.jjxx.modules.sbfb.service.IEqMixStationService;
import cn.jjxx.modules.map.service.ICommonMapService;
/**   
 * @Title: 设备描述
 * @Description: 设备描述
 * @author yw
 * @date 2021-12-23 16:17:39
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/sbfb/eqequipdesc")
@RequiresPathPermission("sbfb:eqequipdesc")
public class EqEquipDescController extends BaseBeanController<EqEquipDesc> {
	
    @Autowired
    protected IEasTOrgBaseunitService easTOrgBaseunitService;
    @Autowired
    protected IEqEquipDescService eqEquipDescService;
    @Autowired
    protected ICommonMapService commonMapService;

    @Autowired
    protected IEqMixStationService eqMixStationService;
    @Autowired
    IDictService Source; 

    @Autowired
    protected IDictService dictService;
	/**
	 * @Description: 根据获取设备描述的实体数据 .<br>
	 * @param id 主键Id.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    public EqEquipDesc get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return eqEquipDescService.selectById(id);
        } else {
            return newModel();
        }
    }

	/**
	 * @Description: 跳转至设备描述的列表界面 .<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

	/**
	 * @Description: 设备描述的列表界面获取列表结果 .<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<EqEquipDesc> entityWrapper = new EntityWrapper<EqEquipDesc>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        entityWrapper.orderBy("date_buy",false);
        String cityCode=request.getParameter("cityCode");
        if(!StringUtils.isEmpty(cityCode)) {
        	entityWrapper.eq("p.city_code", cityCode);
        }
        String manageUnitId=request.getParameter("manageUnitId");
        if(!StringUtils.isEmpty(manageUnitId)) {
        	entityWrapper.eq("t.org_id", manageUnitId);
        }
        String source=request.getParameter("source");
        if(!StringUtils.isEmpty(source)) {
        	entityWrapper.eq("t.source", source);
        }
        String useStatus=request.getParameter("query.useStatus");
        if(!StringUtils.isEmpty(useStatus)) {
        	if("报废".equals(useStatus)) {
            	if(null != queryable.getValue("useStatus")) {
            		queryable.removeCondition("useStatus");
            	}
        		entityWrapper.like("t.use_status", useStatus);
        	}
        }
        

        String size = request.getParameter("page.size");
        if(StringUtils.isEmpty(size)) {
            List<EqEquipDesc> list = eqEquipDescService.selectList(entityWrapper);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("results", list);
            map.put("page", 1);
            map.put("rows", list.size());
            map.put("total", list.size());
            map.put("totalPages", 1);
            String content = JSON.toJSONString(map);
	        StringUtils.printJson(response, content);
        }else {
	        PageJson<EqEquipDesc> pagejson = new PageJson<EqEquipDesc>(eqEquipDescService.list(queryable,entityWrapper));
	        String content = JSON.toJSONString(pagejson);
	        StringUtils.printJson(response, content);
        }
    }

	/**
	 * @Description: 跳转至设备描述的添加界面 .<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        return display("edit");
    }
    
	/**
	 * @Description: 新增设备描述的数据 .<br>
	 * @param eqEquipDesc 设备描述实体类.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") EqEquipDesc eqEquipDesc, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(eqEquipDesc, request, response, result);
    }
	/**
	 * @Description: 跳转至设备描述的更新界面 .<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        EqEquipDesc eqEquipDesc = get(id);
        if(null!=eqEquipDesc) {
        	eqEquipDesc.setUseOrg(eqEquipDesc.getUseOrgCode());
        }
        model.addAttribute("data", eqEquipDesc);
        return display("edit");
    }

	/**
	 * @Description: 修改设备描述的数据 .<br>
	 * @param eqEquipDesc 设备描述实体类.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") EqEquipDesc eqEquipDesc, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(eqEquipDesc, request, response, result);
    }
	/**
	 * @Description: 执行保存设备描述的数据操作 .<br>
	 * @param eqEquipDesc 设备描述实体类.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(EqEquipDesc eqEquipDesc, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(eqEquipDesc, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(eqEquipDesc.getId())) {
                eqEquipDescService.insert(eqEquipDesc);
            } else {
                eqEquipDescService.insertOrUpdate(eqEquipDesc);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

	/**
	 * @Description: 单条删除设备描述 .<br>
	 * @param id 单据Id.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        TableName table = EqEquipDesc.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
        	List<String> ids = Arrays.asList(id.split(","));
        	//得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, ids);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("删除失败,"+quoteMsg);
				return ajaxJson;
			}
            eqEquipDescService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 执行保存设备描述的数据操作 .<br>
	 * @param ids 单据Id集合.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("批量删除成功");
        TableName table = EqEquipDesc.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            //得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, idList);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("批量删除失败,"+quoteMsg);
				return ajaxJson;
			}
            eqEquipDescService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("批量删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 跳转至设备描述的查看界面 .<br>
	 * @param ids 单据Id.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        EqEquipDesc eqEquipDesc = get(id);
        model.addAttribute("data", eqEquipDesc);
        return display("edit");
    }

	/**
	 * @Description: 验证设备描述功能数据的唯一性 .<br>
	 * @param duplicateValid 校验实体类.<br>
	 * @author yw .<br>
	 * @date 2021-12-23 16:17:39.<br>
	 */
    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<EqEquipDesc> entityWrapper = new EntityWrapper<EqEquipDesc>(entityClass);
            valid = eqEquipDescService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }
    
    
    
    
    
    
    
    
    
    /**
     * @Description: 得到可以被审核的单据 .<br>
     * @param bills 单据Id集合.<br>
     * @param status 可操作状态.<br>
     * @author yw .<br>
     * @date 2021-12-23 16:17:39 .<br>
     */
    private List<String> getAllowOptBills(List<String> bills,String status){
    	EntityWrapper<EqEquipDesc> wrapper = new EntityWrapper<EqEquipDesc>();
    	wrapper.in("id", bills);
    	wrapper.eq("status", status);
    	List<EqEquipDesc> list = eqEquipDescService.selectList(wrapper);
    	bills = new ArrayList<String>();
    	for(EqEquipDesc bean:list){
    		bills.add(bean.getId());
    	}
    	return bills;
    }
    
    /**
     * @Description: 设置批量更新参数 .<br>
     * @param bills 可以操作的Id集合.<br>
     * @param newStatus 被修改的状态设置值.<br>
     * @author yw .<br>
     * @date 2021-12-23 16:17:39 .<br>
     */
    private List<EqEquipDesc> setBacthUpdate(List<String> bills,String newStatus){
    	List<EqEquipDesc> list = new ArrayList<EqEquipDesc>();
    	User user = UserUtils.getUser();
    	if(bills.size()>0){
    		list = eqEquipDescService.selectBatchIds(bills);
        	for(EqEquipDesc bean:list){
        		bean.setStatus(Integer.valueOf(newStatus));
        		if(newStatus.equals(String.valueOf(BillConfig.SAVE))||
        				newStatus.equals(String.valueOf(BillConfig.SUBMIT))){
        		}
        	}
    	}
    	return list;
    }
    

    /**
     * 获取设备数和机化站数
     * @return
     */
    @RequestMapping(value = "/getNum", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson getNum(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("查询成功");
        try {
            EntityWrapper<EqEquipDesc> entityWrapper = new EntityWrapper<EqEquipDesc>();
            EntityWrapper<EqMixStation> eqMixStationWrapper = new EntityWrapper<EqMixStation>();
        	String companyid = request.getParameter("companyid");
        	if(!StringUtils.isEmpty(companyid)) {
                entityWrapper.eq("org_id", companyid);
                eqMixStationWrapper.eq("org_id", companyid);
        	}
        	Map<String,Object> map = new HashMap<>();
            entityWrapper.setSqlSelect("count(*) eqNum");
            entityWrapper.eq("status", "0");
            map.put("eqNum",eqEquipDescService.selectObj(entityWrapper));
            
            eqMixStationWrapper.eq("status", "0");
            eqMixStationWrapper.setSqlSelect("count(*) eqNum");
            map.put("stationNum",eqMixStationService.selectObj(eqMixStationWrapper));            
            ajaxJson.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("查询失败");
        }
        return ajaxJson;
    }
    

    /**
     * 获取地市设备数热力值
     * @return
     */
    @RequestMapping(value = "/getHeat", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson getHeat(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("查询成功");
        try {
        	//city_code	city_name	eq_num
        	List<Map<String, Object>> list = eqEquipDescService.selectHeat();
        	if(null!=list&& list.size()>0) {
        		List<Dict> listDists = dictService.selectDictByGroup("EQ_HEAT");
        		if(null!=listDists&& listDists.size()>0) {
        			for (Map<String,Object> map : list) {
						int num=Integer.parseInt(map.get("eq_num").toString());
						for (Dict dict : listDists) {
							String[] val=dict.getValue().split(",");
							int start=0;
							int end=0;
							if(StringUtils.isEmpty(val[0])) {
								end = Integer.parseInt(val[1]);
								if(num<end || 0 == num) {
									map.put("heat", dict.getLabel());
									break;
								}
							}							
							
							if(1 == val.length) {// x,
								start = Integer.parseInt(val[0]);
								if(num >= start) {
									map.put("heat", dict.getLabel());
								}
								break;
							}
							

							start = StringUtils.isEmpty(val[0])? 0: Integer.parseInt(val[0]);
							end = StringUtils.isEmpty(val[1])? 0: Integer.parseInt(val[1]);
							if(num >= start && num <end) {
								map.put("heat", dict.getLabel());
								break;
							}
						}
					}
        		}
        	}
            ajaxJson.setData(list);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("查询失败");
        }
        return ajaxJson;
    }
    

    /**
     * 获取设备按是否为特种设备分类统计
     * @return
     */
    @RequestMapping(value = "/selectEqeTypeCount", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson selectEqeTypeCount(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("查询成功");
        try {
        	String companyid = request.getParameter("companyid");
        	if(StringUtils.isEmpty(companyid)) {
        		companyid = null;
        	}
        	Map<String, Object> map = new HashMap<String, Object>();
    		List<Map> listEqeType = eqEquipDescService.selectEqeTypeCount(companyid);
    		map.put("EqeType", listEqeType);
    		List<Map> listSource = eqEquipDescService.selectEqeSourceCount(companyid);
    		map.put("Source", listSource);
    		List<Map> listUseStatus = eqEquipDescService.selectEqeUseStatusCount(companyid);
    		map.put("UseStatus", listUseStatus);
            ajaxJson.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("查询失败");
        }
        return ajaxJson;
    }
    
    

    /**
     * 一次获取下拉项  设备来源,设备使用状态
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getSelect", method = RequestMethod.GET)
    private AjaxJson getSelect(HttpServletRequest request, HttpServletResponse response) {
    	AjaxJson json = new AjaxJson();
    	json.success("执行成功");

    	List<Dict> dSource = dictService.selectDictByGroup("equipSource");
    	List<Dict> dStatus = dictService.selectDictByGroup("equipUseStatus");
    	List<Object> ListSource =  MapBeanUtil.ListDoSelect(dSource, "label");
    	List<Object> ListStatus =  MapBeanUtil.ListDoSelect(dStatus, "label");
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("equipSource", ListSource);
    	map.put("equipUseStatus", ListStatus);
    	
        json.setData(map);
        return json;
    }
}
